package com.ztgf.sys.api.cms;

import com.ztgf.common.constant.Result;
import com.ztgf.common.enums.CodeEnum;
import com.ztgf.sys.api.common.annotion.SysLogs;
import com.ztgf.sys.models.bo.SysRoleMenuRelationBO;
import com.ztgf.sys.models.service.ISysRoleMenuRelationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 角色菜单关系表控制器
 *
 * @author YUE
 * @Date 2020-05-27 16:37:54
 */

@RestController
@RequestMapping("/cms/sysRoleMenuRelation")
@Slf4j
@Api(value = "SysRoleMenuRelationController",tags = "角色菜单关系表接口")
public class SysRoleMenuRelationController {

    @DubboReference
    private ISysRoleMenuRelationService sysRoleMenuRelationService;

    /**
     *
     * @param menuIds 菜单id集合
     * @param roleId 角色id
     * @return
     */
    @SysLogs(value = "更新或者添加权限")
    @ApiOperation(value = "添加或者更新角色菜单关系表",notes = "添加或者更新角色菜单关系表")
    @PostMapping(value = "/insertOrUpdateRoleMenu")
    public Result insertOrUpdateRoleMenu(String menuIds,Long roleId) {
        List<SysRoleMenuRelationBO> boList = new ArrayList<>();
        String[] menuInfoStr = menuIds.split(",");//所有的菜单信息
        for (String s : menuInfoStr) {
            SysRoleMenuRelationBO sysRoleMenuRelationBO = new SysRoleMenuRelationBO();
            sysRoleMenuRelationBO.setRoleId(roleId);
            List<String> strList = Arrays.asList(s.split("-"));
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < strList.size(); i++) {//权限和菜单取出
                if(i == 0){//菜单id
                    sysRoleMenuRelationBO.setMenuId(Long.parseLong(strList.get(i)));//设置菜单
                    continue;
                }
                if(i == strList.size() - 1){
                    stringBuffer.append(strList.get(i));
                    continue;
                }
                //权限code
                stringBuffer.append(strList.get(i) + ",");
            }
            sysRoleMenuRelationBO.setCode(stringBuffer.toString());
            boList.add(sysRoleMenuRelationBO);
        }
        boolean flag = sysRoleMenuRelationService.insertOrUpdateRoleMenu(boList,roleId);
        if (flag){
            return new Result<>();
        } else {
            return new Result<>(CodeEnum.FAIL_100007);
        }
    }
}
